package jehc.cloud.gen.service.generator;

import jehc.cloud.common.util.ExceptionUtil;
import jehc.cloud.gen.model.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
 * @Desc bootstrap风格方式生成新bootstrap风格方式生成明细页面生成增页面生成
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Data
@Slf4j
public class GeneratorBootPageDetail extends GeneratorUtil {
	
	/**
	 * 生成明细Html及明细JS
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 */
	public void createPageAll(List<XtGeneratorTableColumn> xtGeneratorTableColumnList, XtGenerator xtGenerator){
		createPageBootDetailJs(xtGeneratorTableColumnList, xtGenerator);
		createPageBootDetailHtml(xtGeneratorTableColumnList, xtGenerator);
	}
	//////////////////////1创建bootstrap 明细//////////////////////////
	/**
	 * 1.1.1生成bootstrap页面----detail.JS
	 * 
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 * @return
	 */
	public String createPageBootDetailJs(List<XtGeneratorTableColumn> xtGeneratorTableColumnList,XtGenerator xtGenerator) {
		StringBuffer sb = new StringBuffer();
		sb.append(createPageBootDetailJsContent(xtGeneratorTableColumnList, xtGenerator));
		String path = xtGenerator.getXt_generator_path();
		OutputStreamWriter out = null;
		try {
			out = new OutputStreamWriter(new FileOutputStream(path + lowAllChar_(xtGenerator.getXt_generator_tbname()) + "-detail.js"),"UTF-8");
			try {
				out.write(sb.toString());
			} catch (IOException e) {
				log.error(e.getMessage());
				throw new ExceptionUtil(e.getMessage(), e.getCause());
			}
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
			throw new ExceptionUtil(e.getMessage(), e.getCause());
		} catch (FileNotFoundException e) {
			log.error(e.getMessage());
			throw new ExceptionUtil(e.getMessage(), e.getCause());
		} finally {
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				log.error(e.getMessage());
				throw new ExceptionUtil(e.getMessage(), e.getCause());
			}
		}
		return sb.toString();
	}

	
	/**
	 * 1.1.2创建列表JS内容区域
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 * @return
	 */
	public String createPageBootDetailJsContent(List<XtGeneratorTableColumn> xtGeneratorTableColumnList,XtGenerator xtGenerator) {
		StringBuffer sb = new StringBuffer();
		String root_url = lowOneCharAll_(xtGenerator.getXt_generator_tbname());
		//追加返回方法开始
		sb.append("//返回\r\n");
		sb.append("function goback(){\r\n");
		sb.append("\ttlocation(base_html_redirect+'/"+xtGenerator.getXt_generator_page_package()+"/"+lowAllChar_(xtGenerator.getXt_generator_tbname())+"/"+lowAllChar_(xtGenerator.getXt_generator_tbname())+"-list.html');\r\n");
		sb.append("}\r\n");
		//追加返回方法结束

		sb.append("$(document).ready(function(){\r\n");
		sb.append("\tvar "+getColumnKey(xtGeneratorTableColumnList)+" = GetQueryString(\""+getColumnKey(xtGeneratorTableColumnList)+"\");\r\n");
		sb.append("\t//加载表单数据\r\n");
		sb.append("\tajaxBRequestCallFn("+xtGenerator.getRest_url_prefix()+"+'/"+root_url+"/get/'+"+getColumnKey(xtGeneratorTableColumnList)+",{},function(result){\r\n");
		//赋值
		List<XtGeneratorGridColumn> xtGeneratorGridColumnList = xtGenerator.getXt_Generator_Grid_ColumnList();
		for(int i = 0; i < xtGeneratorGridColumnList.size(); i++){
			XtGeneratorGridColumn xtGeneratorGridColumn = xtGeneratorGridColumnList.get(i);
			sb.append("\t\t$('#"+xtGeneratorGridColumn.getXt_generator_grid_column_name()+"').val(result.data."+xtGeneratorGridColumn.getXt_generator_grid_column_name()+");\r\n");
		}
		//初始化附件右键（Bootstrap风格）
		sb.append(GeneratorPage.createAttachmentBRight(xtGenerator, 2)+"\r\n");
		//创建回显
		sb.append(GeneratorPage.createBAttachmentObject(xtGenerator));
		sb.append("\t});\r\n");
		sb.append("});\r\n");


		
		/////////////////////一对多操作//////////////////////
		if(xtGenerator.getIs_one_to_many().equals("1") && xtGenerator.isIs_main_table()){//如果当前类型为一对多方式并且当前对象为主表 则获取其子表并遍历
			//操作子表
			List<XtGeneratorTableManyToOne> xtGeneratorTableManyToOnes = xtGenerator.getXt_Generator_TableMany_To_OneList();
			for(int i = 0; i < xtGeneratorTableManyToOnes.size(); i++){
				XtGeneratorTableManyToOne xtGeneratorTableManyToOne = xtGeneratorTableManyToOnes.get(i);
				List<XtGeneratorTableColumnManyToOne> xtGeneratorTableColumnManyToOneList = xtGeneratorTableManyToOne.getXt_Generator_Table_ColumnMany_To_OneList();
				////////////////////////////////////////追加子表附件回显开始//////////////////////////////////
				sb.append(GeneratorPage.createBAttachmentOneToManyObject(xtGeneratorTableColumnManyToOneList, xtGenerator, xtGeneratorTableManyToOne, 2));
				////////////////////////////////////////追加子表附件回显结束//////////////////////////////////
			}
		}
		return sb.toString();
	}
	
	
	
	
	/**
	 * 1.2.1生成bootstrap页面----detail.html
	 * 
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 * @return
	 */
	public String createPageBootDetailHtml(List<XtGeneratorTableColumn> xtGeneratorTableColumnList,XtGenerator xtGenerator) {
		StringBuffer sb = new StringBuffer();
		sb.append(createPageBootDetailHtmlContent(xtGeneratorTableColumnList, xtGenerator));
		String path = xtGenerator.getXt_generator_path();
		OutputStreamWriter out = null;
		try {
			out = new OutputStreamWriter(new FileOutputStream(path + lowAllChar_(xtGenerator.getXt_generator_tbname()) + "-detail.html"),"UTF-8");
			try {
				out.write(sb.toString());
			} catch (IOException e) {
				log.error(e.getMessage());
				throw new ExceptionUtil(e.getMessage(), e.getCause());
			}
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
			throw new ExceptionUtil(e.getMessage(), e.getCause());
		} catch (FileNotFoundException e) {
			log.error(e.getMessage());
			throw new ExceptionUtil(e.getMessage(), e.getCause());
		} finally {
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				log.error(e.getMessage());
				throw new ExceptionUtil(e.getMessage(), e.getCause());
			}
		}
		return sb.toString();
	}

	
	/**
	 * 1.2.2创建列表JSP内容区域
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 * @return
	 */
	public String createPageBootDetailHtmlContent(List<XtGeneratorTableColumn> xtGeneratorTableColumnList,XtGenerator xtGenerator) {
		StringBuffer sb = new StringBuffer();
		String root_url = lowOneCharAll_(xtGenerator.getXt_generator_tbname())+"Controller";
		String list_url = "get"+uprepchar(xtGenerator.getXt_generator_tbname())+"ListByCondition";
		List<XtGeneratorSearchFiled> xtGeneratorSearchFileds = xtGenerator.getXt_generator_search_filedList();
		List<String> xt_script_idList = new ArrayList<String>();
		for(int i = 0; i < xtGeneratorSearchFileds.size(); i++){
			XtGeneratorSearchFiled xtGeneratorSearchFiled = xtGeneratorSearchFileds.get(i);
			String xt_script_id = xtGeneratorSearchFiled.getXt_script_id();
			if(null != xt_script_id && !"".equals(xt_script_id)){
				xt_script_idList.add(xt_script_id);
			}
		}
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n");
		sb.append("<!DOCTYPE html SYSTEM \"http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd\">\r\n");
		sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:th=\"http://www.thymeleaf.org\">\r\n");
		sb.append("<head>\r\n");
		sb.append("<meta charset=\"UTF-8\">\r\n");
		sb.append("<script type=\"text/javascript\" src=\"/deng/include/include-css.js\"></script>\r\n");
		sb.append("<title>"+xtGenerator.getXt_generator_tbcomment()+"详情页面</title>\r\n");
		sb.append("</head>\r\n");
		sb.append("<body>\r\n");
		

		sb.append("\t<div class=\"m-portlet\">\r\n");
		sb.append("\t\t<div class=\"m-portlet__head\">\r\n");
		sb.append("\t\t\t<div class=\"m-portlet__head-caption\">\r\n");
		sb.append("\t\t\t\t<div class=\"m-portlet__head-title\">\r\n");
		sb.append("\t\t\t\t\t<span class=\"m-portlet__head-icon m--hide\">\r\n");
		sb.append("\t\t\t\t\t\t<i class=\"la la-gear\"></i>\r\n");
		sb.append("\t\t\t\t\t</span>\r\n");
		sb.append("\t\t\t\t\t<h3 class=\"m-portlet__head-text\">\r\n");
		sb.append("\t\t\t\t\t\t"+xtGenerator.getXt_generator_tbcomment()+"详情\r\n");
		sb.append("\t\t\t\t\t</h3>\r\n");
		sb.append("\t\t\t\t</div>\r\n");
		sb.append("\t\t\t</div>\r\n");
		sb.append("\t\t</div>\r\n");
		
		//表单开始
		sb.append("\t\t<form class=\"m-form m-form--fit m-form--label-align-left m-form--group-seperator-dashed\" id=\"defaultForm\" method=\"post\">\r\n");
		sb.append("\t\t\t<div class=\"m-portlet__body\">\r\n");
		//遍历字段开始
		List<XtGeneratorTableColumnForm> xtGeneratorTableColumnFormList = xtGenerator.getXt_Generator_Table_Column_FormList();
		String tbName = lowfristchar(xtGenerator.getXt_generator_tbname());
		for(int i = 0; i < xtGeneratorTableColumnFormList.size(); i++){
			XtGeneratorTableColumnForm xtGeneratorTableColumnForm = xtGeneratorTableColumnFormList.get(i);
			String column_comment=xtGeneratorTableColumnForm.getColumn_comment();
			String column_name= xtGeneratorTableColumnForm.getColumn_name();
			String column_maxlength = xtGeneratorTableColumnForm.getCharacter_maximum_length();
			String column_hidden = xtGeneratorTableColumnForm.getIsHidden();
			if(null != column_comment && !"".equals(column_comment)){
				column_comment = column_comment.replaceAll("amp;", "");
			}
			
			//验证
			StringBuffer required = new StringBuffer();
			if(xtGeneratorTableColumnForm.getIs_nullable().equals("NO")){
				required.append(" data-bv-notempty data-bv-notempty-message=\"请输入\" ");
			}
			if("int".equals(sqlType2PageType(xtGeneratorTableColumnForm.getData_type()))){
				required.append(" data-bv-numeric data-bv-numeric-message=\"此项为数字类型\" ");
			}
			//如果主键 则隐藏
			if(getColumnFormKey(xtGeneratorTableColumnFormList).equals(xtGeneratorTableColumnForm.getColumn_name())){
				sb.append("\t\t\t\t<div class=\"form-group m-form__group row\" style=\"display:none;\">\r\n");
				sb.append("\t\t\t\t\t<label class=\"col-md-1 col-form-label\">"+column_comment+"</label>\r\n");
				sb.append("\t\t\t\t\t<div class=\"col-md-3\">\r\n");
				sb.append("\t\t\t\t\t\t<input class=\"form-control\" type=\"hidden\" name=\""+column_name+"\" id=\""+column_name+"\" placeholder=\"请输入\">\r\n");
				sb.append("\t\t\t\t\t</div>\r\n");
				sb.append("\t\t\t\t</div>\r\n");
				continue;
			}
			//字段开始（如果该字段隐藏 则div隐藏 并且字段类型为隐含域）
			if("1".equals(column_hidden)){
				sb.append("\t\t\t\t<div class=\"form-group m-form__group row\" style=\"display:none;\">\r\n");
				sb.append("\t\t\t\t\t<label class=\"col-md-1 col-form-label\">"+column_comment+"</label>\r\n");
				sb.append("\t\t\t\t\t<div class=\"col-md-3\">\r\n");
				sb.append("\t\t\t\t\t\t<input class=\"form-control\" type=\"hidden\" id=\""+column_name+"\" name=\""+column_name+"\" "+required.toString()+" placeholder=\"请输入\">\r\n");
				sb.append("\t\t\t\t\t</div>\r\n");
				sb.append("\t\t\t\t</div>\r\n");
			}else{
				sb.append("\t\t\t\t<div class=\"form-group m-form__group row\">\r\n");
				sb.append("\t\t\t\t\t<label class=\"col-md-1 col-form-label\">"+column_comment+"</label>\r\n");
				sb.append("\t\t\t\t\t<div class=\"col-md-3\">\r\n");
				//开始判断类型
				if("String".equals(sqlType2PageType(xtGeneratorTableColumnForm.getData_type()))){
					if(("1").equals(xtGeneratorTableColumnForm.getColumn_type())){
						//文本域
						sb.append("\t\t\t\t\t\t<textarea class=\"form-control\" maxlength=\""+column_maxlength+"\" "+required.toString()+" id='"+column_name+"' name=\""+column_name+"\" placeholder=\"请输入\"></textarea>\r\n");
					}else if(("3").equals(xtGeneratorTableColumnForm.getColumn_type())){
						//下拉框（暂时下拉框采用文本框）
						sb.append("\t\t\t\t\t\t<select class=\"form-control\" maxlength=\""+column_maxlength+"\" "+required.toString()+" id='"+column_name+"' name=\""+column_name+"\" placeholder=\"请选择\"></select>\r\n");
					}else if(("5").equals(xtGeneratorTableColumnForm.getColumn_type())){
						//文件框
						//1添加隐含域即附件编号
						sb.append("\t\t\t\t\t\t<input class=\"form-control\" type=\"hidden\" name=\""+column_name+"\" id=\""+column_name+"\" >\r\n");
						sb.append("\t\t\t\t\t\t<img src = \"/deng/images/default/add_d.png\" class=\"img\" width=\"96\"  height=\"96\"  id=\""+column_name+"_pic\">\r\n");
					}else{
						//文本框
						sb.append("\t\t\t\t\t\t<input class=\"form-control\" type=\"text\" maxlength=\""+column_maxlength+"\" "+required.toString()+" id='"+column_name+"' name=\""+column_name+"\" placeholder=\"请输入\">\r\n");
					}
				}else if("Date".equals(sqlType2PageType(xtGeneratorTableColumnForm.getData_type())) || "datetime".equals(sqlType2PageType(xtGeneratorTableColumnForm.getData_type())) || "time".equals(sqlType2PageType(xtGeneratorTableColumnForm.getData_type()))){
					sb.append("\t\t\t\t\t\t<input class=\"form_datetime form-control\" name=\""+column_name+"\" "+required.toString()+" id='"+column_name+"' placeholder=\"请选择时间\" >\r\n");
				}else if("int".equals(sqlType2PageType(xtGeneratorTableColumnForm.getData_type()))){
					//数字框
					sb.append("\t\t\t\t\t\t<input class=\"form-control\" maxlength=\""+column_maxlength+"\" "+required.toString()+" id='"+column_name+"' name=\""+column_name+"\" placeholder=\"请输入\">\r\n");
				}else if("BigDecimal".equals(sqlType2PageType(xtGeneratorTableColumnForm.getData_type()))){
					//数字框
					sb.append("\t\t\t\t\t\t<input class=\"form-control\" maxlength=\""+column_maxlength+"\" "+required.toString()+" id='"+column_name+"' name=\""+column_name+"\" placeholder=\"请输入\">\r\n");
				}else{
					//文本框
					sb.append("\t\t\t\t\t\t<input class=\"form-control\" type=\"text\" maxlength=\""+column_maxlength+"\" "+required.toString()+" id='"+column_name+"' name=\""+column_name+"\" placeholder=\"请输入\">\r\n");
				}
				//结束判断类型
				sb.append("\t\t\t\t\t</div>\r\n");
				sb.append("\t\t\t\t</div>\r\n");
			}
			//字段结束
		}
		//遍历字段结束
		
		/////////////////////一对多操作（主表中追加子表标识）//////////////////////
		if(xtGenerator.getIs_one_to_many().equals("1") && xtGenerator.isIs_main_table()){//如果当前类型为一对多方式并且当前对象为主表 则获取其子表并遍历
			List<XtGeneratorTableManyToOne> xtGeneratorTableManyToOnes = xtGenerator.getXt_Generator_TableMany_To_OneList();
			for(int i = 0; i < xtGeneratorTableManyToOnes.size(); i++){
				XtGeneratorTableManyToOne xtGeneratorTableManyToOne = xtGeneratorTableManyToOnes.get(i);
				//当前子表单的form标识
				String remvoed_flag = lowfristchar(xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_name())+"_removed_flag";
				String formNumber = lowOneCharAll_(xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_name())+"FormNumber";
				sb.append("\t\t\t\t<div class=\"form-group m-form__group row\" style=\"display:none;\">\r\n");
				sb.append("\t\t\t\t\t<div class=\"col-md-3\">\r\n");
				sb.append("\t\t\t\t\t\t<input class=\"form-control\" type=\"hidden\" name=\""+remvoed_flag+"\" id=\""+remvoed_flag+"\" >\r\n");
				sb.append("\t\t\t\t\t\t<input class=\"form-control\" type=\"hidden\" name=\""+formNumber+"\" id=\""+formNumber+"\" >\r\n");
				sb.append("\t\t\t\t\t</div>\r\n");
				sb.append("\t\t\t\t</div>\r\n");
			}
		}
		
		//////////////////一对多子表字段遍历（初始化显示一个子表单）///////////////////////////
		if(xtGenerator.getIs_one_to_many().equals("1") && xtGenerator.isIs_main_table()){//如果当前类型为一对多方式并且当前对象为主表 则获取其子表并遍历
			//操作子表
			List<XtGeneratorTableManyToOne> xtGeneratorTableManyToOnes = xtGenerator.getXt_Generator_TableMany_To_OneList();
			for(int i = 0; i < xtGeneratorTableManyToOnes.size(); i++){
				XtGeneratorTableManyToOne xtGeneratorTableManyToOne = xtGeneratorTableManyToOnes.get(i);
				String upcharTableName = uprepchar(xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_name());//开头转大写的表名（类名）
				//获取当前子表单的
				lowOneCharAll_(xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_name());
				String lowfristTableName = lowfristchar(xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_name());
				sb.append("\t\t\t\t<!-- 一对多子表开始（"+xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_name_zh()+"） -->\r\n");
				sb.append("\t\t\t\t<div class=\"page-header\">\r\n");
				sb.append("\t\t\t\t\t<h4>"+xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_name_zh()+"</h4>\r\n");
				sb.append("\t\t\t\t</div>\r\n");
				List<XtGeneratorTableColumnManyToOne> xtGeneratorTableColumnManyToOneList = xtGeneratorTableManyToOne.getXt_Generator_Table_ColumnMany_To_OneList();
				//追加子表字段信息
				sb.append("\t\t\t\t<div class=\"form_"+lowfristTableName+"\">\r\n");//标注子表中根目录名称 用于JS操作APPEND 开始
				sb.append("\t\t\t\t</div>\r\n");//标注子表中根目录名称 用于JS操作APPEND 结束
				sb.append("\t\t\t\t<!-- 一对多子表结束（"+xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_name_zh()+"） -->\r\n");
			}
		}
		sb.append("\t\t\t</div>\r\n");
		//追加按钮
		sb.append("\t\t\t<div class=\"m-portlet__foot m-portlet__foot--fit\">\r\n");
		//左边按钮开始
		sb.append("\t\t\t\t<div class=\"m-form__actions m-form__actions--right\">\r\n");
		sb.append("\t\t\t\t\t<div class=\"row\">\r\n");
		sb.append("\t\t\t\t\t\t<div class=\"col m--align-left\">\r\n");
		sb.append("\t\t\t\t\t\t\t<a class=\"btn btn-secondary m-btn m-btn--custom m-btn--icon\" href=\"javascript:goback()\">返回</a>\r\n");
		sb.append("\t\t\t\t\t\t</div>\r\n");
		//左边按钮结束
		//右边按钮开始
		sb.append("\t\t\t\t\t\t<div class=\"col m--align-right\">\r\n");
		sb.append("\t\t\t\t\t\t</div>\r\n");
		sb.append("\t\t\t\t\t</div>\r\n");
		sb.append("\t\t\t\t</div>\r\n");
		sb.append("\t\t\t</div>\r\n");
		//右边按钮结束
		sb.append("\t\t</form>\r\n");
		//表单结束
		sb.append("\t</div>\r\n");
		
		sb.append("</body>\r\n");
		
		if(xtGenerator.getIs_one_to_many().equals("1") && xtGenerator.isIs_main_table()){
			sb.append("<script type=\"text/javascript\">\r\n");
			sb.append("\tvar "+lowfristchar(xtGenerator.getXt_generator_tbname())+"Obj = '${"+lowfristchar(xtGenerator.getXt_generator_tbname())+"JSON}';\r\n");
			sb.append("\ttry{\r\n");
			sb.append("\t\t"+lowfristchar(xtGenerator.getXt_generator_tbname())+"Obj = eval(\"(\"+"+lowfristchar(xtGenerator.getXt_generator_tbname())+"Obj+\")\");\r\n");
			sb.append("\t}catch(e){\r\n");
			sb.append("\t}\r\n");
			sb.append("</script>\r\n");
		}
		//导入JS支持
		sb.append("<script type=\"text/javascript\" src=\"/deng/include/include.js\"></script>\r\n");
		sb.append("<script type=\"text/javascript\" src=\"/deng/view/"+xtGenerator.getXt_generator_page_package()+"/"+lowAllChar_(xtGenerator.getXt_generator_tbname())+"/"+lowAllChar_(xtGenerator.getXt_generator_tbname())+"-detail.js\"></script> \r\n");
		sb.append("</html>\r\n");
		/////////////////////////内容结束////////////////////////
		return sb.toString();
	}
}
